"""
服务器管理路由
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional
import time
import aiohttp

from ..models import (
    ServersListResponse, ServerResponse, ServerRegisterRequest,
    BaseResponse, ErrorResponse
)
from ..storage import data_manager, SubscriptionServer
from ..logger import logger
from ..utils import generate_id, validate_url

router = APIRouter()


async def check_server_health(server: SubscriptionServer) -> bool:
    """检查服务器健康状态"""
    try:
        timeout = aiohttp.ClientTimeout(total=10)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            headers = {}
            if server.api_key:
                headers['Authorization'] = f'Bearer {server.api_key}'
            
            # 尝试访问健康检查端点
            health_url = f"{server.url.rstrip('/')}/health"
            async with session.get(health_url, headers=headers) as response:
                return response.status == 200
                
    except Exception as e:
        logger.debug(f"Server {server.name} health check failed: {e}")
        return False


@router.get("/servers", response_model=ServersListResponse)
async def get_servers():
    """获取所有订阅服务器"""
    try:
        # 从存储获取服务器数据
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        # 转换为响应模型
        server_responses = [
            ServerResponse(
                id=server_data['id'],
                name=server_data['name'],
                url=server_data['url'],
                status=server_data['status'],
                last_check=server_data.get('last_check'),
                check_interval=server_data['check_interval'],
                consecutive_errors=server_data.get('consecutive_errors', 0)
            )
            for server_data in servers_list
        ]
        
        return ServersListResponse(
            servers=server_responses,
            total=len(server_responses),
            message=f"Found {len(server_responses)} servers"
        )
        
    except Exception as e:
        logger.error(f"Failed to get servers: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve servers")


@router.get("/servers/{server_id}", response_model=ServerResponse)
async def get_server(server_id: str):
    """获取指定服务器详情"""
    try:
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        # 查找指定服务器
        server_data = None
        for server in servers_list:
            if server['id'] == server_id:
                server_data = server
                break
        
        if not server_data:
            raise HTTPException(status_code=404, detail="Server not found")
        
        return ServerResponse(
            id=server_data['id'],
            name=server_data['name'],
            url=server_data['url'],
            status=server_data['status'],
            last_check=server_data.get('last_check'),
            check_interval=server_data['check_interval'],
            consecutive_errors=server_data.get('consecutive_errors', 0)
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get server {server_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve server")


@router.post("/servers", response_model=BaseResponse)
async def register_server(server_request: ServerRegisterRequest):
    """注册新的订阅服务器"""
    try:
        # 验证URL格式
        if not validate_url(server_request.url):
            raise HTTPException(status_code=400, detail="Invalid URL format")
        
        # 检查服务器是否已存在
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        for existing_server in servers_list:
            if existing_server['url'] == server_request.url:
                raise HTTPException(
                    status_code=409, 
                    detail="Server with this URL already exists"
                )
            if existing_server['name'] == server_request.name:
                raise HTTPException(
                    status_code=409, 
                    detail="Server with this name already exists"
                )
        
        # 创建新服务器记录
        new_server = SubscriptionServer(
            id=generate_id(),
            name=server_request.name,
            url=server_request.url.rstrip('/'),
            api_key=server_request.api_key,
            status="offline",  # 初始状态
            last_check=None,
            check_interval=server_request.check_interval,
            consecutive_errors=0
        )
        
        # 尝试检查服务器健康状态
        is_healthy = await check_server_health(new_server)
        new_server.status = "online" if is_healthy else "offline"
        new_server.last_check = time.time()
        
        # 保存到存储
        servers_list.append(new_server.to_dict())
        servers_data['servers'] = servers_list
        servers_data['last_update'] = time.time()
        
        await data_manager.servers_storage.save(servers_data)
        
        logger.info(f"Registered new server: {new_server.name} ({new_server.url})")
        
        return BaseResponse(
            message=f"Server {new_server.name} registered successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to register server: {e}")
        raise HTTPException(status_code=500, detail="Failed to register server")


@router.put("/servers/{server_id}/check", response_model=BaseResponse)
async def check_server(server_id: str):
    """手动检查服务器状态"""
    try:
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        # 查找指定服务器
        server_index = None
        server_data = None
        for i, server in enumerate(servers_list):
            if server['id'] == server_id:
                server_index = i
                server_data = server
                break
        
        if server_data is None:
            raise HTTPException(status_code=404, detail="Server not found")
        
        # 创建服务器对象进行健康检查
        server_obj = SubscriptionServer.from_dict(server_data)
        is_healthy = await check_server_health(server_obj)
        
        # 更新服务器状态
        old_status = server_data['status']
        new_status = "online" if is_healthy else "offline"
        
        servers_list[server_index]['status'] = new_status
        servers_list[server_index]['last_check'] = time.time()
        
        if new_status == "offline":
            servers_list[server_index]['consecutive_errors'] = \
                servers_list[server_index].get('consecutive_errors', 0) + 1
        else:
            servers_list[server_index]['consecutive_errors'] = 0
        
        # 保存更新
        servers_data['servers'] = servers_list
        servers_data['last_update'] = time.time()
        await data_manager.servers_storage.save(servers_data)
        
        status_change = f" (changed from {old_status})" if old_status != new_status else ""
        logger.info(f"Server {server_data['name']} status: {new_status}{status_change}")
        
        return BaseResponse(
            message=f"Server {server_data['name']} is {new_status}{status_change}"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to check server {server_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to check server")


@router.delete("/servers/{server_id}", response_model=BaseResponse)
async def delete_server(server_id: str):
    """删除订阅服务器"""
    try:
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        # 查找并删除服务器
        server_found = False
        server_name = ""
        
        for i, server in enumerate(servers_list):
            if server['id'] == server_id:
                server_name = server['name']
                servers_list.pop(i)
                server_found = True
                break
        
        if not server_found:
            raise HTTPException(status_code=404, detail="Server not found")
        
        # 保存更新
        servers_data['servers'] = servers_list
        servers_data['last_update'] = time.time()
        await data_manager.servers_storage.save(servers_data)
        
        logger.info(f"Deleted server: {server_name}")
        
        return BaseResponse(
            message=f"Server {server_name} deleted successfully"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to delete server {server_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete server")


@router.post("/servers/check-all", response_model=BaseResponse)
async def check_all_servers():
    """检查所有服务器状态"""
    try:
        servers_data = await data_manager.servers_storage.load()
        servers_list = servers_data.get('servers', [])
        
        if not servers_list:
            return BaseResponse(message="No servers to check")
        
        # 检查所有服务器
        checked_count = 0
        online_count = 0
        
        for i, server_data in enumerate(servers_list):
            server_obj = SubscriptionServer.from_dict(server_data)
            is_healthy = await check_server_health(server_obj)
            
            old_status = server_data['status']
            new_status = "online" if is_healthy else "offline"
            
            servers_list[i]['status'] = new_status
            servers_list[i]['last_check'] = time.time()
            
            if new_status == "offline":
                servers_list[i]['consecutive_errors'] = \
                    servers_list[i].get('consecutive_errors', 0) + 1
            else:
                servers_list[i]['consecutive_errors'] = 0
                online_count += 1
            
            checked_count += 1
        
        # 保存更新
        servers_data['servers'] = servers_list
        servers_data['last_update'] = time.time()
        await data_manager.servers_storage.save(servers_data)
        
        logger.info(f"Checked {checked_count} servers, {online_count} online")
        
        return BaseResponse(
            message=f"Checked {checked_count} servers, {online_count} online, {checked_count - online_count} offline"
        )
        
    except Exception as e:
        logger.error(f"Failed to check all servers: {e}")
        raise HTTPException(status_code=500, detail="Failed to check servers")
